﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Text;
using System.Data;

using Library.Common;
using Library.Bll;
using HanhuaMicroCredit.BLL;
namespace HanhuaMicroCredit.Admin.Controllers
{
    public class OperateTotalController : Controller
    {
        #region //For日志 表名转换

        #endregion

        #region // 通用操作 (添加|根据主表id,附表多次添加|修改|启用|禁用|主附表关联查询)

        [HttpPost]
        [ValidateInput(false)]
        public ContentResult Add(int? dtnum, string name, string url, FormCollection fc)
        {
            #region //添加
            try
            {
                string[] arrName = DencryptHelper.Decrypt(name).Split(',');
                //
                Dictionary<string, object> d = new Dictionary<string, object>();
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf("t0_") > -1)
                    {
                        d.Add(s.Replace("t0_", ""), fc[s]);
                    }
                }
                //主表添加
                if (!dtnum.HasValue)
                {
                    dtnum = 0;
                }

                Database database = (Database)dtnum.Value;
                //邮轮行程
                /*
                if (fc["selDayCb"] != null && fc["selDayCb"].ToString()=="on")
                { 
                    int count =Convert.ToInt32(fc["t6_selDay"].ToString());
                    for(int i=1 ;i<count;i++)
                    {
                        string rec = new CruiseProController().CopyTripDetail(pId.ToString(), i.ToString()).Content;
                    }
                }*/
                int pId = CommonBLL.Add(database, arrName[0], d);
                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "添加", "添加id:" + pId);
                //
                if (arrName.Length > 1)
                {
                    //附表添加
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        string fieldVal = "";
                        string fieldName = "";
                        string fieldMore = "t" + i + "_fm_";
                        string delPriGdt = "";
                        foreach (string s in fc.Keys)
                        {
                            if (s.IndexOf(fieldMore) > -1)
                            {
                                fieldVal = fc[s];
                                fieldName = s;
                                delPriGdt = "('" + fieldVal.Trim().Replace(",", "','") + "')";
                            }
                        }
                        ////机票价格添加，先删除重复价格
                        //int delPri = 0;
                        //if (arrName[i] == "Free_DtBase_Air")
                        //{
                        //    delPri = FreeBase.delRepeatAirPri(fc["t" + i + "_InfoGuid"], fc["t" + i + "_suppId"], fc["t" + i + "_PriceType"], delPriGdt);
                        //}

                        if (fieldVal != "")
                        {
                            foreach (string val in fieldVal.Split(','))
                            {
                                if (!string.IsNullOrEmpty(val))
                                {
                                    Dictionary<string, object> nextDic = new Dictionary<string, object>();

                                    nextDic.Add("pId", pId);
                                    nextDic.Add(fieldName.Replace(fieldMore, ""), val);
                                    if (arrName[i] == "CruisePBase_Trip_Photo")
                                    {
                                        string title = fc[val.Split('/')[2].Split('.')[0]].ToString();
                                        nextDic.Add("title", title);
                                    }

                                    foreach (string s in fc.Keys)
                                    {
                                        string first = "t" + i + "_";
                                        if (s.IndexOf(first) > -1 && s.IndexOf(fieldMore) <= -1)
                                            nextDic.Add(s.Replace(first, ""), fc[s]);
                                    }
                                    int logid = CommonBLL.Add(database, arrName[i], nextDic);
                                    //日志
                                    InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "添加", "添加id:" + logid);
                                }
                            }
                        }
                    }
                }
                //复制邮轮行程
                /*
                if (fc["selDayCb"] != null && fc["selDayCb"].ToString()=="on")
                { 
                    int count =Convert.ToInt32(fc["t6_selDay"].ToString());
                    for(int i=1 ;i<count;i++)
                    {
                        string rec = new CruiseProController().CopyTripDetail(pId.ToString(), i.ToString()).Content;
                    }
                }*/


                if (arrName[0] == "Team_Base")
                {
                    url += "&tId=" + pId;
                    //自动添加一条销售价格类型
                    d = new Dictionary<string, object>();
                    d.Add("pId", pId);
                    d.Add("vId", "1");//默认销售价格
                    CommonBLL.Add("Team_CSellPrice", d);
                    //自动添加一条价格类型(成人1，儿童2)
                    for (int i = 1; i <= 2; i++)
                    {
                        d = new Dictionary<string, object>();
                        //0,48,1
                        d.Add("pId", pId);
                        d.Add("masterType", "0");
                        d.Add("fatherType", "48");
                        d.Add("childType", "1");
                        d["childType"] = i;
                        CommonBLL.Add("Team_PriType", d);
                    }
                }
                if (arrName[0] == "Team_DtBase")
                {
                    url += "&mId=" + pId;
                }
                if (arrName[0] == "Supp_Unit")
                {
                    url += "&Id=" + pId;
                }
                if (arrName[0] == "Team_Groups")
                {
                    url += "&Id=" + pId;
                }
                if (arrName[0] == "Team_other")
                {
                    url += "&Id=" + pId;
                }
                if (arrName[0] == "Flight_Info")
                {
                    url += "&next=1";
                }
                //if (arrName[0] == "Free_DtBase_Air")
                //{
                //    TourBase.upFreeMinPrice(fc["lineid"].ToString());
                //}
                //if (arrName.Length > 1)
                //{
                //    if (arrName[1] == "Free_DtBase_Air")
                //    { TourBase.upFreeMinPrice(fc["lineid"].ToString()); }
                //}
                if (fc["popInfo"] != null)//在本页弹出结果
                    return Content(JUIResult.ResultMsg("1", "操作成功"));
                else
                    return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }




        [HttpPost]
        public ContentResult AddMore(int? dtnum, string name, string url, FormCollection fc)
        {
            #region //根据主表id,附表值多次添加
            try
            {
                Database database = (Database)dtnum.Value;
                name = DencryptHelper.Decrypt(name);
                string fieldVal = "";
                string fieldName = "";
                string fieldMore = "t0_fm_";
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf(fieldMore) > -1)
                    {
                        fieldVal = fc[s];
                        fieldName = s;
                    }
                }
                if (fieldVal != "")
                {
                    foreach (string val in fieldVal.Split(','))
                    {
                        if (!string.IsNullOrEmpty(val))
                        {
                            Dictionary<string, object> nextDic = new Dictionary<string, object>();
                            nextDic.Add(fieldName.Replace(fieldMore, ""), val);
                            foreach (string s in fc.Keys)
                            {
                                string first = "t0_";
                                if (s.IndexOf(first) > -1 && s.IndexOf(fieldMore) <= -1)
                                    nextDic.Add(s.Replace(first, ""), fc[s]);
                            }
                            int logid = CommonBLL.Add(database, name, nextDic);
                            //日志
                            InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(name), "添加", "添加id:" + logid);
                        }
                    }
                }
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }



        [HttpPost]
        [ValidateInput(false)]
        public ContentResult Edit(int? dtnum, int id, string name, string url, FormCollection fc, string toMore)
        {
            #region //修改
            try
            {
                string[] arrName = DencryptHelper.Decrypt(name).Split(',');
                //
                Dictionary<string, object> d = new Dictionary<string, object>();
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf("t0_") > -1)
                    {
                        d.Add(s.Replace("t0_", ""), fc[s]);
                    }
                }
                //
                string condition = "id=" + id;
                if (Utils.StrToInt(toMore, 0) == 1)
                    condition = "isvalid = 1 and pid=" + id;
                //主表修改
                if (!dtnum.HasValue)
                {
                    dtnum = 0;
                }
                if (arrName[0] == "Supp_Unit")
                {
                    Dictionary<string, object> old = CommonBLL.GetModel("Supp_Unit", "*", "id=" + id);
                    string log = "";
                    foreach (string key in fc.Keys)
                    {

                        if (key.IndexOf("t0") > -1 && old[key.Replace("t0_", "")].ToString().Trim() != fc[key].ToString().Trim())
                            log += getSuppInfo(key) + "：" + old[key.Replace("t0_", "")] + "-->" + fc[key] + "<br/>";

                        if (key == "t1_fm_Destid")
                        {
                            string destList = selectControlBLL.getChildDt("Supp_LineDest", id.ToString(), "", "1", "destId");
                            if (destList != fc[key].ToString().Trim())
                                log += getSuppInfo(key) + "：" + destList + "-->" + fc[key] + "<br/>";
                        }
                    }


                    old.Clear();
                    old.Add("OperLog", log);
                    old.Add("model", "基本信息");
                    old.Add("SuppId", id);
                    if (log != "")
                    {
                        int j = CommonBLL.Add("Supp_OperLogs", old);
                    }
                }
                Database database = (Database)dtnum.Value;
                int r = CommonBLL.Update(database, arrName[0], d, condition);
                int pId = id;
                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "修改", "修改id:" + pId);
                //
                if (arrName.Length > 1)
                {
                    //附表修改
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        string fieldVal = "";
                        string fieldName = "";
                        string fieldMore = "t" + i + "_fm_";

                        //同一表多个字段识别
                        string typeMore = "t" + i + "_tp_";
                        string typeName = "";
                        string typeVal = "";
                        foreach (string s in fc.Keys)
                        {
                            if (s.IndexOf(fieldMore) > -1)
                            {
                                fieldVal = fc[s];
                                fieldName = s;
                            }
                            if (s.IndexOf(typeMore) > -1)
                            {
                                typeVal = fc[s];
                                typeName = s;
                            }
                        }
                        string delConditions = string.Format("pid={0}", pId);
                        /** tn_2012_10_18 修改代码 start **/
                        /** 原代码 **
                        if (typeName != "")
                        delConditions += string.Format(" and {0} = '{1}'", typeName.Replace(typeMore, ""), typeVal);
                        ** 原代码 **/
                        if (typeName != "")
                        {
                            //配置多个值，以逗号分隔
                            if (typeVal.IndexOf(',') < 0)
                                delConditions += string.Format(" and {0} = '{1}'", typeName.Replace(typeMore, ""), typeVal);
                            else
                                delConditions += string.Format(" and {0} IN ({1})", typeName.Replace(typeMore, ""), typeVal);

                        }
                        /** tn_2012_10_18 修改代码 end **/
                        CommonBLL.Delete(database, arrName[i], delConditions);
                        if (fieldVal != "")
                        {
                            foreach (string val in fieldVal.Split(','))
                            {
                                Dictionary<string, object> nextDic = new Dictionary<string, object>();
                                nextDic.Add("pId", pId);
                                nextDic.Add(fieldName.Replace(fieldMore, ""), val);
                                foreach (string s in fc.Keys)
                                {
                                    string first = "t" + i + "_";
                                    if (s.IndexOf(first) > -1 && s.IndexOf(fieldMore) <= -1)
                                    {
                                        if (s.IndexOf(typeMore) > -1)
                                            nextDic.Add(s.Replace(typeMore, ""), fc[s]);
                                        else
                                            nextDic.Add(s.Replace(first, ""), fc[s]);
                                    }
                                }
                                string condtions = string.Format("pid = {0} and {1} = '{2}'", pId, fieldName.Replace(fieldMore, ""), val);

                                if (CommonBLL.Exists(database, arrName[i], condtions))
                                {
                                    Dictionary<string, object> update = new Dictionary<string, object>();
                                    update.Add("isValid", 1);
                                    //油轮图片
                                    if (arrName[i] == "CruisePBase_Trip_Photo")
                                    {
                                        string title = fc[val.Split('/')[2].Split('.')[0]].ToString();
                                        update.Add("title", title);
                                    }
                                    CommonBLL.Update(database, arrName[i], update, condtions);
                                }
                                else
                                {
                                    if (arrName[i] == "CruisePBase_Trip_Photo")
                                    {
                                        string title = fc[val.Split('/')[2].Split('.')[0]].ToString();
                                        nextDic.Add("title", title);
                                    }
                                    CommonBLL.Add(database, arrName[i], nextDic);
                                }
                                //日志
                                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "修改", condtions);
                            }
                        }
                    }
                }

                if (fc["popInfo"] != null)//在本页弹出结果
                    return Content(JUIResult.ResultMsg("1", "操作成功"));
                else
                    return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }
        private string getSuppInfo(string key)
        {
            Dictionary<string, object> info = new Dictionary<string, object>();
            info.Add("t0_CompanyName", "供应商公司名称");
            info.Add("t0_Code", "供应商编码");
            info.Add("t0_suppCode", "供应商简拼");
            info.Add("t0_Level", "供应商级别");
            info.Add("t0_ShortName", "简称/品牌名");
            info.Add("t0_address", "供应商地址");
            info.Add("t0_zip", "邮编");
            info.Add("t0_Tel", "电话");
            info.Add("t0_Fax", "传真");
            info.Add("t0_licenseno", "经营许可证号");
            info.Add("t0_ProManager", "产品经理");
            info.Add("t0_destType", "目的地类型");
            info.Add("t0_GroupID", "供应商类型");
            info.Add("t0_StartCity", "产品出发地");
            info.Add("t0_PartCompany", "签约分公司");
            info.Add("t1_fm_Destid", "所属目的地");
            info.Add("t0_CheckEndTime", "合同截至日期");
            info.Add("t0_CurrentState", "供应商状态");
            info.Add("t0_CheckType", "财务结算类型");
            info.Add("t0_ProType", "产品类型");
            info.Add("t0_SuppIntro", "供应商简介");
            info.Add("t0_ProfIntro", "返佣信息");
            info.Add("t0_Rmarks", "备注信息");

            return info[key].ToString();

        }
        [HttpPost]
        public ContentResult EditMore(int? dtnum, int id, string name, string url, FormCollection fc)
        {
            #region //修改
            try
            {
                name = DencryptHelper.Decrypt(name);
                //主表添加
                if (!dtnum.HasValue)
                {
                    dtnum = 0;
                }
                Database database = (Database)dtnum.Value;
                //
                string fieldVal = "";
                string fieldName = "";
                string fieldMore = "t0_fm_";
                foreach (string s in fc.Keys)
                {
                    if (s.IndexOf(fieldMore) > -1)
                    {
                        fieldVal = fc[s];
                        fieldName = s;
                    }
                }
                CommonBLL.Delete(database, name, "pId=" + id);
                if (fieldVal != "")
                {
                    foreach (string val in fieldVal.Split(','))
                    {
                        Dictionary<string, object> nextDic = new Dictionary<string, object>();
                        nextDic.Add("pId", id);
                        nextDic.Add(fieldName.Replace(fieldMore, ""), val);

                        string condtions = string.Format("pid = {0} and {1} = '{2}'", id, fieldName.Replace(fieldMore, ""), val);

                        if (CommonBLL.Exists(database, name, condtions))
                        {
                            string sql = string.Format("update {1} set IsValid = 1 Where id = (select top 1  id  from {1} where {0}) ", condtions, name);
                            CommonBLL.ExecuteSQL4NonQuery(sql);
                        }
                        else
                        {
                            CommonBLL.Add(database, name, nextDic);
                        }
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(name), "修改", condtions);
                    }
                }
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }
        [HttpPost]
        public ContentResult SetOpen(string dtnum, string ids, string name, string url)
        {
            #region //启用
            try
            {
                if (string.IsNullOrWhiteSpace(ids))
                    return Content(JUIResult.ResultMsg("ids为空必须选择一条记录，报该错及时通知技术人员"));

                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);
                Dictionary<string, object> d = new Dictionary<string, object>();
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

                if (arrName[0] == "Free_Flight_Info")
                {
                    //启用
                    ids = Utils.ClearLastChar(ids);
                    condition = ids.Replace(",", "or").Replace("|", "and");//

                    //(lineId=" + dr["Lineid"] + "| pid=" + dr["caseId"] + " | busiType=14 )
                    string caseId = ids.Split('|')[1].Replace("pid", "id");//lineId=

                    string sql = ids.Split('|')[0].Replace("(", "");//lineId=
                    list = CommonBLL.GetList("Flight_CaseInfo", "distinct pid", "", "id in (select pid from " + arrName[0] + " where " + condition + ")");
                    if (list.Count != 1)
                        return Content("不能同时启用两个概要");


                    d.Add("isvalid", 0);
                    sql = sql + " and PID not in (select ID from Flight_CaseInfo where PID=(  select pid from Flight_CaseInfo where " + caseId + "))";
                    int count = CommonBLL.Update(database, arrName[0], d, "busiType=14 and isValid=1 and " + sql);


                }
                if (arrName[0] == "Free_DtBase_Air")
                {

                    condition = ids.Replace(",", "or");
                }

                //
                //房间号管理状态
                d.Clear();
                if (url.IndexOf("roomstate") > -1)
                    d.Add("roomstate", 1);
                else
                    d.Add("isvalid", 1);

                //启用
                if (!string.IsNullOrWhiteSpace(ids))
                    CommonBLL.Update(database, arrName[0], d, condition);
                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "启用", "启用ids:" + ids);

                //入职方案删除级联价格
                if (arrName[0] == "Free_Case")
                {
                    string sql = @"update  Team_DtBase_Price_Foot set isValid=1 where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") )";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除底价", count + "|" + sql);

                    sql = @"update Team_DtBase_Price_Add set IsValid=1 where pId in (
                        Select id From Team_DtBase_Price_Foot where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") ) )";
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);

                    sql = "update Team_DtBase  set IsValid=1 where CaseId=" + ids;
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);
                }

                //if (arrName[0].ToLower() == "mkt_coupon")
                //{

                //    string sql = "select priceuse,orderId from mkt_coupon where State='已锁定' and id in (" + ids + ")";
                //    DataTable dtt = CommonBLL.ExecuteSQL4Dataset(sql, null).Tables[0];
                //    foreach (DataRow drow in dtt.Rows)
                //    {
                //        using (IDbTransaction tran = CommonBLL.BeginTransaction())
                //        {
                //            try
                //            {

                //                string s = Finance.NoncashPay(tran, Convert.ToInt32(drow[1].ToString().Split('-')[0]), -decimal.Parse(drow[0].ToString()), "订单回调", 1, "", "解锁代金券");
                //                tran.Commit();
                //                InsLogBll.InsertLog("订单状态", "使用积分", s);

                //            }
                //            catch (Exception ex)
                //            {
                //                InsLogBll.InsertLog("订单状态", "使用积分错误", ex.ToString());
                //                tran.Rollback();
                //            }
                //        }
                //    }
                //    sql = "update mkt_coupon set state='已验证'  where id in (" + ids + ")";
                //    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);

                //    InsLogBll.InsertLog("cp", "解锁代金券", count + "|" + sql);
                //}
                if (arrName.Length > 1)
                {
                    //附表启用
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        CommonBLL.Update(database, arrName[i], d, string.Format("pId in ({0})", ids));
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "启用", "启用pId:" + ids);
                    }
                }
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }


        [HttpPost]
        public ContentResult pitModPrice(string name, string url, FormCollection fc)
        {
            string arrName = DencryptHelper.Decrypt(name);
            string[] idList = Utils.ClearLastChar(fc["hdIdlist"].ToString().Trim()).Split(',');

            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("InfoId", fc["InfoGuid"]);
            int newid = CommonBLL.Add("Flight_Pri", d);

            foreach (string id in idList)
            {
                //改同组为一个价格
                if (fc["operType"].ToString() == "mod")
                {
                    string valId = idList[0];
                    string up = "update Free_DtBase_Air set SuppID=" + fc[valId + "_SuppID"] + ",BasePrice=" + fc[valId + "_BasePrice"];
                    up += ",ChlidBasePrice=" + fc[valId + "_ChlidBasePrice"] + ",SellAddPrice=" + fc[valId + "_SellAddPrice"];
                    up += ",ChlidTax=" + fc[valId + "_ChlidTax"] + ",BaseTax=" + fc[valId + "_BaseTax"] + ",CabinType='" + fc[valId + "_CabinType"] + "'";
                    up += ",PriceType=" + fc[valId + "_PriceType"] + ",TicketDays=" + fc[valId + "_TicketDays"] + ",SameAddPrice=" + fc[valId + "_SameAddPrice"] + " where id=" + id;
                    int i = CommonBLL.ExecuteSQL4NonQuery(up, null);
                    if (i <= 0)
                    {
                        return Content(JUIResult.ResultMsg("提交失败"));
                    }
                }
                else
                {
                    int del = CommonBLL.Delete("Free_DtBase_Air", "id in (" + Utils.ClearLastChar(fc["hdIdlist"].ToString().Trim()) + ")");

                    d.Clear();
                    d.Add("pid", newid);
                    d.Add("manId", fc["manId"]);
                    d.Add("InfoGuid", fc["InfoGuid"]);
                    d.Add("gdt", fc[id + "_gdt1"]);
                    d.Add("SuppID", fc[id + "_SuppID"]);
                    d.Add("BasePrice", fc[id + "_BasePrice"]);
                    d.Add("ChlidBasePrice", fc[id + "_ChlidBasePrice"]);
                    d.Add("SellAddPrice", fc[id + "_SellAddPrice"]);
                    d.Add("ChlidTax", fc[id + "_ChlidTax"]);
                    d.Add("BaseTax", fc[id + "_BaseTax"]);
                    d.Add("CabinType", fc[id + "_CabinType"]);
                    d.Add("PriceType", fc[id + "_PriceType"]);
                    d.Add("TicketDays", fc[id + "_TicketDays"]);
                    d.Add("SameAddPrice", fc[id + "_SameAddPrice"]);
                    del = CommonBLL.Add("Free_DtBase_Air", d);


                }

            }
            return Content(JUIResult.ResultUrl(HttpUtility.UrlDecode(url)));
        }

        [HttpPost]
        public ContentResult Deletes(string dtnum, string ids, string name, string url)
        {
            #region //禁用
            try
            {
                if (string.IsNullOrWhiteSpace(ids))
                    return Content(JUIResult.ResultMsg("ids为空必须选择一条记录，报该错及时通知技术人员"));

                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                url = DencryptHelper.Decrypt(url);

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);
                if (arrName[0] == "Free_Flight_Info")
                {

                    string[] idList = ids.Split(',');

                    string newIds = "";

                    for (int i = 0; i < idList.Length; i++)
                    {
                        string one = idList[i].Split('|')[0] + ")";
                        newIds += one + " | ";

                    }
                    if (newIds != "")
                        newIds = Utils.ClearLastChar(newIds.Trim()).Replace("|", "or");

                    condition = "id in (select id from " + arrName[0] + " where " + newIds + ")";
                }

                if (arrName[0] == "SMS_send")
                {
                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from SMS_send where " + condition, null);

                }

                Dictionary<string, object> d = new Dictionary<string, object>();
                //房间号管理状态
                if (url.IndexOf("roomstate") > -1)
                    d.Add("roomstate", 0);
                else
                    d.Add("isvalid", 0);

                //主表删除
                if (!string.IsNullOrWhiteSpace(ids))
                    CommonBLL.Update(database, arrName[0], d, condition);

                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "禁用", "禁用ids:" + ids);

                if (arrName[0] == "Supp_LinkMan")
                {
                    DataTable dtt = CommonBLL.ExecuteSQL4Dataset("select suppId,LinkmanName from Supp_LinkMan where id=" + ids, null).Tables[0];

                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from Supp_LinkMan where id=" + ids, null);
                    if (i > 0)
                    {
                        Dictionary<string, object> data1 = new Dictionary<string, object>();
                        data1.Add("OperLog", "删除联系人：" + dtt.Rows[0][1] + "|" + ids);
                        data1.Add("model", "联系人信息");
                        data1.Add("SuppId", dtt.Rows[0][0].ToString());
                        int j = CommonBLL.Add("Supp_OperLogs", data1);

                    }

                }

                //机票价格级联删除,团期和酒店的日期也要一并进行删除
                if (arrName[0] == "Free_DtBase_Air")
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Length; i++)
                    {
                        //是否存在该方案日期的价格
                        string sql = @"select count(*) from Free_DtBase_Air where  
                        --InfoGuid='b94daecd-557e-481e-8aca-e1aeb6a41b11'
                        gDt=(select gDt from Free_DtBase_Air where id={0}) and
                        InfoGuid=(select InfoGuid from Free_DtBase_Air where id={1}) and IsValid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        int count = (int)CommonBLL.ExecuteSQL4Scalar(sql, null);

                        sql = @"update dbo.Team_DtBase_Dt Set  IsValid=0
                            where lineId in ( 
                            select distinct lineid from Free_Flight_Info where PID in 
                            (select ID from Flight_Info where Guid=(select InfoGuid from Free_DtBase_Air where id={0} and IsValid=0))
                            ) and gDt=(select gDt from Free_DtBase_Air where id={1} and IsValid=0)  and isvalid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        if (count == 0)
                        {
                            count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                            InsLogBll.InsertLog("free", "团期和价格级联删除", count + "|" + sql);
                        }

                    }
                }
                //入职方案删除级联价格
                if (arrName[0] == "Free_Case")
                {
                    string sql = @"update  Team_DtBase_Price_Foot set isValid=0 where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") )";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除底价", count + "|" + sql);

                    sql = @"update Team_DtBase_Price_Add set IsValid=0 where pId in (
                        Select id From Team_DtBase_Price_Foot where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") ) )";
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);

                    sql = "update Team_DtBase  set IsValid=0 where CaseId=" + ids;
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);
                }
                if (arrName[0].ToLower() == "mkt_coupon")
                {
                    string sql = "delete mkt_coupon  where id in (" + ids + ")";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("cp", "删除代金券", count + "|" + sql);
                }

                if (arrName.Length > 1)
                {
                    //附表删除
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        CommonBLL.Delete(database, arrName[i], string.Format("pId in ({0})", ids));
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "禁用", "禁用pId:" + ids);
                    }
                }
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }

        [HttpPost]
        public ContentResult Delete1(string dtnum, string ids1, string name, string url)
        {
            #region //禁用
            try
            {
                if (string.IsNullOrWhiteSpace(ids1))
                    return Content(JUIResult.ResultMsg("ids为空必须选择一条记录，报该错及时通知技术人员"));

                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                //url = HttpUtility.UrlEncode(url);
                string ids = ids1;
                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);
                if (arrName[0] == "Free_Flight_Info")
                {

                    string[] idList = ids.Split(',');

                    string newIds = "";

                    for (int i = 0; i < idList.Length; i++)
                    {
                        string one = idList[i].Split('|')[0] + ")";
                        newIds += one + " | ";

                    }
                    if (newIds != "")
                        newIds = Utils.ClearLastChar(newIds.Trim()).Replace("|", "or");

                    condition = "id in (select id from " + arrName[0] + " where " + newIds + ")";
                }

                if (arrName[0] == "SMS_send")
                {
                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from SMS_send where " + condition, null);

                }


                Dictionary<string, object> d = new Dictionary<string, object>();
                //房间号管理状态
                if (url.IndexOf("roomstate") > -1)
                    d.Add("roomstate", 0);
                else
                    d.Add("isvalid", 0);

                //主表删除
                if (!string.IsNullOrWhiteSpace(ids1))
                    CommonBLL.Update(database, arrName[0], d, condition);

                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "禁用", "禁用ids:" + ids);

                if (arrName[0] == "Supp_LinkMan")
                {
                    DataTable dtt = CommonBLL.ExecuteSQL4Dataset("select suppId,LinkmanName from Supp_LinkMan where id=" + ids, null).Tables[0];

                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from Supp_LinkMan where id=" + ids, null);
                    if (i > 0)
                    {
                        Dictionary<string, object> data1 = new Dictionary<string, object>();
                        data1.Add("OperLog", "删除联系人：" + dtt.Rows[0][1] + "|" + ids);
                        data1.Add("model", "联系人信息");
                        data1.Add("SuppId", dtt.Rows[0][0].ToString());
                        int j = CommonBLL.Add("Supp_OperLogs", data1);

                    }

                }

                //机票价格级联删除,团期和酒店的日期也要一并进行删除
                if (arrName[0] == "Free_DtBase_Air")
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Length; i++)
                    {
                        //是否存在该方案日期的价格
                        string sql = @"select count(*) from Free_DtBase_Air where  
                        --InfoGuid='b94daecd-557e-481e-8aca-e1aeb6a41b11'
                        gDt=(select gDt from Free_DtBase_Air where id={0}) and
                        InfoGuid=(select InfoGuid from Free_DtBase_Air where id={1}) and IsValid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        int count = (int)CommonBLL.ExecuteSQL4Scalar(sql, null);

                        sql = @"update dbo.Team_DtBase_Dt Set  IsValid=0
                            where lineId in ( 
                            select distinct lineid from Free_Flight_Info where PID in 
                            (select ID from Flight_Info where Guid=(select InfoGuid from Free_DtBase_Air where id={0} and IsValid=0))
                            ) and gDt=(select gDt from Free_DtBase_Air where id={1} and IsValid=0)  and isvalid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        if (count == 0)
                        {
                            count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                            InsLogBll.InsertLog("free", "团期和价格级联删除", count + "|" + sql);
                        }

                    }
                }
                //入职方案删除级联价格
                if (arrName[0] == "Free_Case")
                {
                    string sql = @"update  Team_DtBase_Price_Foot set isValid=0 where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") )";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除底价", count + "|" + sql);

                    sql = @"update Team_DtBase_Price_Add set IsValid=0 where pId in (
                        Select id From Team_DtBase_Price_Foot where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") ) )";
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);

                    sql = "update Team_DtBase  set IsValid=0 where CaseId=" + ids;
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);
                }
                if (arrName[0].ToLower() == "mkt_coupon")
                {
                    string sql = "delete mkt_coupon  where id in (" + ids + ")";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("cp", "删除代金券", count + "|" + sql);
                }

                if (arrName.Length > 1)
                {
                    //附表删除
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        CommonBLL.Delete(database, arrName[i], string.Format("pId in ({0})", ids));
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "禁用", "禁用pId:" + ids);
                    }
                }
                //if (arrName[0] == "Finance_CusFrom")
                //{
                //    Dictionary<string, object> fCus = CommonBLL.GetModel("Finance_CusFrom", "*", Utils.StrToInt(ids, 0));
                //    if (fCus != null)
                //    {
                //        using (IDbTransaction tran = CommonBLL.BeginTransaction())
                //        {
                //            Finance.Pay(tran, Convert.ToInt32(fCus["orderId"]), 1, Convert.ToInt32(fCus["payment"]), -Convert.ToDecimal(fCus["total"]));
                //            tran.Commit();
                //        }

                //    }
                //}
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }

        [HttpPost]
        public ContentResult SetOpen1(string dtnum, string ids1, string name, string url)
        {
            #region //启用
            try
            {
                if (string.IsNullOrWhiteSpace(ids1))
                    return Content(JUIResult.ResultMsg("ids为空必须选择一条记录，报该错及时通知技术人员"));

                string ids = ids1;
                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);

                if (arrName[0] == "Free_Flight_Info")
                {

                    #region 1084 动态查询/1085 打包产品 只能添加一个概要
                    //ids=(LIneId=1072 and PID=35 and FlightSeq1=1|manId=1),(LIneId=1072 and PID=35 and FlightSeq1=1|manId=1)

                    string[] idList = ids.Split(',');

                    string newIds = "";
                    string newManId = "";

                    for (int i = 0; i < idList.Length; i++)
                    {
                        string one = idList[i].Split('|')[0] + ")";
                        newIds += one + " | ";
                        newManId = Utils.ClearLastChar(idList[i].Split('|')[1].Trim().Replace("manId=", ""));



                        string lineId = idList[i].TrimEnd().Replace("and", "|").Split('|')[0].TrimEnd().ToLower().Replace("(lineid=", "");

                        string PID = idList[i].TrimEnd().Replace("and", "|").Split('|')[1].TrimStart().TrimEnd().ToLower().Replace("pid=", "");

                        if (HttpUtility.UrlDecode(url).IndexOf("busiType=15") < 0)
                        {
                            //油轮不判断
                            string isSelect = "select FreeType from Team_Base where id=" + lineId +
                                "  select distinct pid from Flight_info where id in (select Pid  from Free_Flight_Info where lineid =" + lineId + " and isValid=1)";

                            DataSet ds = CommonBLL.ExecuteSQL4Dataset(isSelect);

                            if (ds.Tables[0].Rows[0][0].ToString() == "1020")//1085
                            {


                                if (ds.Tables[1].Rows.Count > 1)
                                {
                                    return Content(JUIResult.ResultMsg("自由行打包线路只能添加一个航班概要，请禁用目前航班方案"));
                                }
                                else if (ds.Tables[1].Rows.Count == 1)
                                {
                                    if (ds.Tables[1].Rows[0][0].ToString() != newManId)
                                        return Content(JUIResult.ResultMsg("自由行打包线路只能添加一个航班概要，请禁用目前航班方案"));

                                }
                            }
                        }

                    }
                    if (newIds != "")
                        newIds = Utils.ClearLastChar(newIds.Trim()).Replace("|", "or");

                    condition = "id in (select id from " + arrName[0] + " where " + newIds + ")";
                    #endregion
                }
                if (arrName[0] == "Free_DtBase_Air")//
                {

                    condition = ids.Replace(",", "or");
                }

                //
                Dictionary<string, object> d = new Dictionary<string, object>();
                //房间号管理状态
                if (url.IndexOf("roomstate") > -1)
                    d.Add("roomstate", 1);
                else
                    d.Add("isvalid", 1);

                //启用
                if (!string.IsNullOrWhiteSpace(ids))
                    CommonBLL.Update(database, arrName[0], d, condition);
                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "启用", "启用ids:" + ids);

                //入职方案删除级联价格
                if (arrName[0] == "Free_Case")
                {
                    string sql = @"update  Team_DtBase_Price_Foot set isValid=1 where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") )";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除底价", count + "|" + sql);

                    sql = @"update Team_DtBase_Price_Add set IsValid=1 where pId in (
                        Select id From Team_DtBase_Price_Foot where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") ) )";
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);

                    sql = "update Team_DtBase  set IsValid=1 where CaseId=" + ids;
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);
                }

                //if (arrName[0].ToLower() == "mkt_coupon")
                //{

                //    string sql = "select priceuse,orderId from mkt_coupon where State='已锁定' and id in (" + ids + ")";
                //    DataTable dtt = CommonBLL.ExecuteSQL4Dataset(sql, null).Tables[0];
                //    foreach (DataRow drow in dtt.Rows)
                //    {
                //        using (IDbTransaction tran = CommonBLL.BeginTransaction())
                //        {
                //            try
                //            {

                //                string s = Finance.NoncashPay(tran, Convert.ToInt32(drow[1].ToString().Split('-')[0]), -decimal.Parse(drow[0].ToString()), "订单回调", 1, "", "解锁代金券");
                //                tran.Commit();
                //                InsLogBll.InsertLog("订单状态", "使用积分", s);

                //            }
                //            catch (Exception ex)
                //            {
                //                InsLogBll.InsertLog("订单状态", "使用积分错误", ex.ToString());
                //                tran.Rollback();
                //            }
                //        }
                //    }
                //    sql = "update mkt_coupon set state='已验证'  where id in (" + ids + ")";
                //    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);

                //    InsLogBll.InsertLog("cp", "解锁代金券", count + "|" + sql);
                //}
                if (arrName.Length > 1)
                {
                    //附表启用
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        CommonBLL.Update(database, arrName[i], d, string.Format("pId in ({0})", ids));
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "启用", "启用pId:" + ids);
                    }
                }
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }

        [HttpPost]
        public ContentResult Delete(string dtnum, string ids, string name, string url)
        {
            #region //禁用
            try
            {
                if(string.IsNullOrWhiteSpace(ids))
                    return Content(JUIResult.ResultMsg("ids为空必须选择一条记录，报该错及时通知技术人员"));

                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                //url = HttpUtility.UrlEncode(url);

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);
                if (arrName[0] == "Free_Flight_Info")
                {
                    ids = Utils.ClearLastChar(ids);
                    condition = ids.Replace(",", "or").Replace("|", "and");
                }

                if (arrName[0] == "SMS_send")
                {
                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from SMS_send where " + condition, null);

                }


                Dictionary<string, object> d = new Dictionary<string, object>();
                //房间号管理状态
                if (url.IndexOf("roomstate") > -1)
                    d.Add("roomstate", 0);
                else
                    d.Add("isvalid", 0);

                //主表删除
                if (!string.IsNullOrWhiteSpace(ids))
                    CommonBLL.Update(database, arrName[0], d, condition);

                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[0]), "禁用", "禁用ids:" + ids);

                if (arrName[0] == "Supp_LinkMan")
                {
                    DataTable dtt = CommonBLL.ExecuteSQL4Dataset("select suppId,LinkmanName from Supp_LinkMan where id=" + ids, null).Tables[0];

                    int i = CommonBLL.ExecuteSQL4NonQuery("delete from Supp_LinkMan where id=" + ids, null);
                    if (i > 0)
                    {
                        Dictionary<string, object> data1 = new Dictionary<string, object>();
                        data1.Add("OperLog", "删除联系人：" + dtt.Rows[0][1] + "|" + ids);
                        data1.Add("model", "联系人信息");
                        data1.Add("SuppId", dtt.Rows[0][0].ToString());
                        int j = CommonBLL.Add("Supp_OperLogs", data1);

                    }

                }

                //机票价格级联删除,团期和酒店的日期也要一并进行删除
                if (arrName[0] == "Free_DtBase_Air")
                {
                    string[] idList = ids.Split(',');
                    for (int i = 0; i < idList.Length; i++)
                    {
                        //是否存在该方案日期的价格
                        string sql = @"select count(*) from Free_DtBase_Air where  
                        --InfoGuid='b94daecd-557e-481e-8aca-e1aeb6a41b11'
                        gDt=(select gDt from Free_DtBase_Air where id={0}) and
                        InfoGuid=(select InfoGuid from Free_DtBase_Air where id={1}) and IsValid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        int count = (int)CommonBLL.ExecuteSQL4Scalar(sql, null);

                        sql = @"update dbo.Team_DtBase_Dt Set  IsValid=0
                            where lineId in ( 
                            select distinct lineid from Free_Flight_Info where PID in 
                            (select ID from Flight_Info where Guid=(select InfoGuid from Free_DtBase_Air where id={0} and IsValid=0))
                            ) and gDt=(select gDt from Free_DtBase_Air where id={1} and IsValid=0)  and isvalid=1";
                        sql = string.Format(sql, idList[i], idList[i]);
                        if (count == 0)
                        {
                            count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                            InsLogBll.InsertLog("free", "团期和价格级联删除", count + "|" + sql);
                        }

                    }
                }
                //入职方案删除级联价格
                if (arrName[0] == "Free_Case")
                {
                    string sql = @"update  Team_DtBase_Price_Foot set isValid=0 where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") )";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除底价", count + "|" + sql);

                    sql = @"update Team_DtBase_Price_Add set IsValid=0 where pId in (
                        Select id From Team_DtBase_Price_Foot where pId in(
                        SELECT id FROM Team_DtBase_Price where pId in(
                        SELECT id FROM Team_DtBase where CaseId=" + ids + ") ) )";
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);

                    sql = "update Team_DtBase  set IsValid=0 where CaseId=" + ids;
                    count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("free", "入住方案级联删除加价", count + "|" + sql);
                }
                if (arrName[0].ToLower() == "mkt_coupon")
                {
                    string sql = "delete mkt_coupon  where id in (" + ids + ")";
                    int count = CommonBLL.ExecuteSQL4NonQuery(sql, null);
                    InsLogBll.InsertLog("cp", "删除代金券", count + "|" + sql);
                }

                if (arrName.Length > 1)
                {
                    //附表删除
                    for (int i = 1; i < arrName.Length; i++)
                    {
                        CommonBLL.Delete(database, arrName[i], string.Format("pId in ({0})", ids));
                        //日志
                        InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName[i]), "禁用", "禁用pId:" + ids);
                    }
                }
                //if (arrName[0] == "Finance_CusFrom")
                //{
                //    Dictionary<string, object> fCus = CommonBLL.GetModel("Finance_CusFrom", "*", Utils.StrToInt(ids, 0));
                //    if (fCus != null)
                //    {
                //        using (IDbTransaction tran = CommonBLL.BeginTransaction())
                //        {
                //            Finance.Pay(tran, Convert.ToInt32(fCus["orderId"]), 1, Convert.ToInt32(fCus["payment"]), -Convert.ToDecimal(fCus["total"]));
                //            tran.Commit();
                //        }

                //    }
                //}
                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }
        [HttpPost]
        public ContentResult bingCp(string ids, string userId)
        {
            #region 绑定代金券
            try
            {

                //
                string condition = "update Mkt_Coupon set UserId='" + userId + "' where  id in (" + ids.TrimEnd(',') + ")";


                //主表删除
                int i = CommonBLL.ExecuteSQL4NonQuery(condition, null);
                //日志
                InsLogBll.InsertLog("代金券", "绑定", "绑定ids:" + ids + "|" + i);


                return Content(i.ToString());
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
            #endregion
        }

        [HttpPost]
        public ContentResult setStatus(string dtnum, string ids, string name, string url, int state)
        {
            #region //禁用
            try
            {
                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                //url = HttpUtility.UrlEncode(url);

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);

                Dictionary<string, object> nextDic = new Dictionary<string, object>();

                nextDic.Add("State", state);

                //改状态
                int i = CommonBLL.Update(database, arrName[0], nextDic, condition);
                //日志
                InsLogBll.InsertLog(arrName[0], "改状态" + i, "改状态ids:" + ids);


                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }
        /// <summary>
        /// 单品推荐
        /// </summary>
        /// <param name="dtnum"></param>
        /// <param name="ids"></param>
        /// <param name="name"></param>
        /// <param name="url"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult setChoose(string dtnum, string ids, string name, string url, int state)
        {
            #region //禁用
            try
            {
                string[] arrName = DencryptHelper.Decrypt(name).Split(',');

                //url = HttpUtility.UrlEncode(url);

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                ids = Utils.ChkSQL(ids);
                //
                string condition = string.Format("id in ({0})", ids);

                Dictionary<string, object> nextDic = new Dictionary<string, object>();

                nextDic.Add("Ischoose", state);

                //改状态
                int i = CommonBLL.Update(database, arrName[0], nextDic, condition);
                //日志
                InsLogBll.InsertLog(arrName[0], "改状态" + i, "改状态ids:" + ids);


                //
                return Content(JUIResult.ResultUrl(url));
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }

        [HttpPost]
        public ContentResult isExist(string name, string field, string value, string oper, string dtnum, string isvalid, string id)
        {
            #region //禁用
            try
            {
                string arrName = DencryptHelper.Decrypt(name);
                //0 表示=,1表示>=,2表示<=,3表示like
                switch (oper)
                {
                    case "0":
                        oper = "=";
                        break;
                    case "1":
                        oper = ">=";
                        break;
                    case "2":
                        oper = "<=";
                        break;
                    case "3":
                        oper = "like";
                        break;
                }
                dtnum = string.IsNullOrWhiteSpace(dtnum) ? "1" : dtnum;
                isvalid = string.IsNullOrWhiteSpace(isvalid) ? "0,1" : isvalid;

                int dt = Utils.StrToInt(dtnum, 1) - 1;
                Database database = (Database)dt;
                //
                string condition = string.Format("isValid in ({0}) and " + field + " " + oper + " " + value, isvalid);

                condition = string.IsNullOrWhiteSpace(id) ? condition : condition + " and id<>" + id;
                //主表
                string res = CommonBLL.Exists(database, arrName, condition) ? "1" : "0";



                //日志
                InsLogBll.InsertLog(selectControlBLL.ConvertToTableName(arrName), "是否存在", "是否存在:" + res);

                return Content(res);
            }
            catch (Exception ex)
            {
                return Content(JUIResult.ResultMsg(ex.Message));
            }
            #endregion
        }

        //线路管理查询
        [HttpPost]
        public ActionResult SearchListDistinct(
            string tName,
            string pars,
            string name,
            string control,
            int pageindex,
            int pagesize,
            string dtnum,
            string states
            )
        {
            #region //主附表关联查询
            List<string> compare = new List<string>();
            compare.Add("=");//__0
            compare.Add(">=");//__1
            compare.Add("<=");//__2
            compare.Add("like");//__3
            compare.Add("in");//__4
            compare.Add("not in");//__5
            //
            string[] arrName = DencryptHelper.Decrypt(tName).Split(',');
            string selectColumns = string.Format(" distinct {0}.ID,{0}.name,{0}.destType,{0}.proBeType,{0}.startCity,{0}.TourDay,{0}.startPrice,"
            + "{0}.createDate,{0}.UPDATEdate,{0}.createUserId,{0}.isvalid ,{0}.cpMaxPrice,{0}.ttsMaxPrice", arrName[0]);//可以放到页面


            string sortColumns = string.Format("id desc", arrName[0]);//可以放到页面
            //
            StringBuilder conditions = new StringBuilder();
            string isvalid = "1";
            if (states != "")
                isvalid = Utils.StrToInt(states, 0).ToString();
            else
                isvalid = "0,1";
            conditions.AppendFormat(" {0}.isValid in ({1}) ", arrName[0], isvalid);
            if (arrName.Length > 1)
            {
                //附表关联
                for (int i = 1; i < arrName.Length; i++)
                {
                    conditions.AppendFormat(" And {0}.id={1}.pId  ", arrName[0], arrName[i]);
                }
            }
            pars = HttpUtility.UrlDecode(pars);//
            string[] par = pars.Split(',');
            if (par.Length > 0)
            {
                List<string> l = new List<string>();
                foreach (string s in name.Split(','))
                    l.Add(s);
                int i = 0;
                foreach (string s in par)
                {
                    if (!Utils.StrIsNullOrEmpty(s))
                    {
                        string f = l[i];
                        int type = Utils.StrToInt(f.Substring(f.Length - 1, 1), 0);
                        string filed = f.Substring(2, f.Length - 5);
                        string forTable = arrName[Utils.StrToInt(f.Substring(0, 1), 0)];
                        string val = s.Trim();
                        val = HttpUtility.UrlDecode(val);
                        val = Utils.ChkSQL(val);
                        if (type == 3)
                        {
                            val = " '%" + val + "%'";
                        }
                        else if (type == 4 || type == 5)
                        {
                            val = val.Replace("_", ",");
                            val = "(" + val + ")";
                        }
                        else
                        {
                            val = " '" + val + "'";
                        }
                        conditions.AppendFormat(" And {0}.[{2}] {3} {1} ", forTable, val, filed, compare[type]);
                    }

                    i++;
                }
            }
            //
            PagedInfo p = new PagedInfo();
            p.PageSize = pagesize;
            p.PageIndex = pageindex;
            int database = Utils.StrToInt(dtnum, 1) - 1;
            PagedResult<DataSet> pR = CommonBLL.GetPagedList((Database)database, DencryptHelper.Decrypt(tName), selectColumns, sortColumns, conditions.ToString(), p);
            //
            return PartialView("~/Views/" + control + ".ascx", pR);
            #endregion
        }

        //邮轮线路管理查询
        [HttpPost]
        public ActionResult SearchCruiseListDistinct(
            string tName,
            string pars,
            string name,
            string control,
            int pageindex,
            int pagesize,
            string dtnum,
            string states
            )
        {
            #region //主附表关联查询
            List<string> compare = new List<string>();
            compare.Add("=");//__0
            compare.Add(">=");//__1
            compare.Add("<=");//__2
            compare.Add("like");//__3
            compare.Add("in");//__4
            compare.Add("not in");//__5
            //
            string[] arrName = DencryptHelper.Decrypt(tName).Split(',');
            string selectColumns = string.Format(" distinct {0}.ID,{0}.name,{0}.destType,{0}.proBeType,{0}.sCity,{0}.tDays,{0}.createDate,{0}.UPDATEdate,{0}.createUserId,{0}.isvalid,{0}.title,{0}.keywords,{0}.desriptions,{0}.topManager ", arrName[0]);//可以放到页面


            string sortColumns = string.Format("id desc", arrName[0]);//可以放到页面
            //
            StringBuilder conditions = new StringBuilder();
            string isvalid = "1";
            if (states != "")
                isvalid = Utils.StrToInt(states, 0).ToString();
            else
                isvalid = "0,1";
            conditions.AppendFormat(" {0}.isValid in ({1}) ", arrName[0], isvalid);
            if (arrName.Length > 1)
            {
                //附表关联
                for (int i = 1; i < arrName.Length; i++)
                {
                    conditions.AppendFormat(" And {0}.id={1}.pId  ", arrName[0], arrName[i]);
                }
            }
            pars = HttpUtility.UrlDecode(pars);//
            string[] par = pars.Split(',');
            if (par.Length > 0)
            {
                List<string> l = new List<string>();
                foreach (string s in name.Split(','))
                    l.Add(s);
                int i = 0;
                foreach (string s in par)
                {
                    if (!Utils.StrIsNullOrEmpty(s))
                    {
                        string f = l[i];
                        int type = Utils.StrToInt(f.Substring(f.Length - 1, 1), 0);
                        string filed = f.Substring(2, f.Length - 5);
                        string forTable = arrName[Utils.StrToInt(f.Substring(0, 1), 0)];
                        string val = s.Trim();
                        val = HttpUtility.UrlDecode(val);
                        val = Utils.ChkSQL(val);
                        if (type == 3)
                        {
                            val = " '%" + val + "%'";
                        }
                        else if (type == 4 || type == 5)
                        {
                            val = val.Replace("_", ",");
                            val = "(" + val + ")";
                        }
                        else
                        {
                            val = " '" + val + "'";
                        }
                        conditions.AppendFormat(" And {0}.[{2}] {3} {1} ", forTable, val, filed, compare[type]);
                    }

                    i++;
                }
            }
            //
            PagedInfo p = new PagedInfo();
            p.PageSize = pagesize;
            p.PageIndex = pageindex;
            int database = Utils.StrToInt(dtnum, 1) - 1;
            PagedResult<DataSet> pR = CommonBLL.GetPagedList((Database)database, DencryptHelper.Decrypt(tName), selectColumns, sortColumns, conditions.ToString(), p);
            //
            return PartialView("~/Views/" + control + ".ascx", pR);
            #endregion
        }

        [HttpPost]
        public ActionResult SearchList(
            string tName,
            string pars,
            string name,
            string control,
            int pageindex,
            int pagesize,
            string dtnum,
            string states
            )
        {
            #region //主附表关联查询
            List<string> compare = new List<string>();
            compare.Add("=");//__0
            compare.Add(">=");//__1
            compare.Add("<=");//__2
            compare.Add("like");//__3
            compare.Add("in");//__4
            compare.Add("not in");//__5
            //
            string[] arrName = DencryptHelper.Decrypt(tName).Split(',');
            string selectColumns = string.Format("{0}.*", arrName[0]);//可以放到页面


            string sortColumns = string.Format("{0}.id desc", arrName[0]);//可以放到页面
            //
            StringBuilder conditions = new StringBuilder();
            string isvalid = "1";
            if (states != "")
                isvalid = Utils.StrToInt(states, 0).ToString();
            else
                isvalid = "0,1";
            conditions.AppendFormat(" {0}.isValid in ({1}) ", arrName[0], isvalid);
            if (arrName.Length > 1)
            {
                //附表关联
                for (int i = 1; i < arrName.Length; i++)
                {
                    conditions.AppendFormat(" And {0}.id={1}.pId  ", arrName[0], arrName[i]);
                }
            }
            /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 Start**/
            //保存加号在pars中出现的位置
            string flag_tn = string.Empty;
            if (pars.IndexOf('+') > 0)
            {
                string[] temp_tn = pars.Split(',');
                for (int i = 0; i < temp_tn.Length; i++)
                {
                    if (temp_tn[i] == "+")
                    {
                        if (flag_tn.Length > 0)
                        {
                            flag_tn += ",";
                        }
                        flag_tn += i.ToString();
                    }
                }
            }
            /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 End**/

            pars = HttpUtility.UrlDecode(pars);//

            string[] par = pars.Split(',');

            /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 Start**/
            if (!string.IsNullOrEmpty(flag_tn))
            {
                string[] tn_index = flag_tn.Split(',');
                for (int i = 0; i < tn_index.Length; i++)
                {
                    int index_ = Int16.Parse(tn_index[i]);
                    par[index_] = "+";
                }
            }
            /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 End**/
            if (par.Length > 0)
            {
                List<string> l = new List<string>();
                foreach (string s in name.Split(','))
                    l.Add(s);
                int i = 0;
                foreach (string s in par)
                {
                    if (!Utils.StrIsNullOrEmpty(s))
                    {
                        string f = l[i];
                        int type = Utils.StrToInt(f.Substring(f.Length - 1, 1), 0);
                        string filed = f.Substring(2, f.Length - 5);
                        string forTable = arrName[Utils.StrToInt(f.Substring(0, 1), 0)];
                        string val = s.Trim();
                        val = HttpUtility.UrlDecode(val);
                        /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 Start**/
                        if (flag_tn.Length > 0 && s.Trim() == "+")
                        {
                            val = s.Trim();
                        }
                        /**tn_2012-6-27 加号在解码时会被过滤，所以手动添加 End**/
                        val = Utils.ChkSQL(val);
                        if (type == 3)
                        {
                            val = " '%" + val + "%'";
                        }
                        else if (type == 4 || type == 5)
                        {
                            val = val.Replace("_", ",");
                            val = "(" + val + ")";
                        }
                        else
                        {
                            val = " '" + val + "'";
                        }
                        conditions.AppendFormat(" And {0}.[{2}] {3} {1} ", forTable, val, filed, compare[type]);
                    }

                    i++;
                }
            }
            //
            PagedInfo p = new PagedInfo();
            p.PageSize = pagesize;
            p.PageIndex = pageindex;
            int database = Utils.StrToInt(dtnum, 1) - 1;
            PagedResult<DataSet> pR = CommonBLL.GetPagedList((Database)database, DencryptHelper.Decrypt(tName), selectColumns, sortColumns, conditions.ToString(), p);
            //
            return PartialView("~/Views/" + control + ".ascx", pR);
            #endregion
        }
        #endregion

        #region //[控件]日历
        public ActionResult RetCalendar(
            string isTwo,
            string curDT,
            string lineId
            )
        {
            List<string> list = new List<string>();
            list.Add(isTwo);
            list.Add(curDT);
            list.Add(lineId);
            return PartialView("~/Views/Shared/Calendar.ascx", list);
        }
        #endregion

        #region //[控件]日历
        public ActionResult RetCalendarFree(
            string isTwo,
            string curDT,
            string lineId, string tid, string type
            )
        {
            List<string> list = new List<string>();
            list.Add(isTwo);
            list.Add(curDT);
            list.Add(lineId);
            list.Add(tid);
            if (type.Split(',').Length >= 3)
            {//title里要显示中文的酒店名称，为防止乱码，此处需要做编码解码处理，但是日历控件里有翻页，又需要一个未经解码的酒店名，所以此处同时保留编过码和未编码的两种酒店名
                list.Add(type.Split(',')[0] + "," + type.Split(',')[1] + "," + type.Split(',')[2] + "," + Server.UrlDecode(type.Split(',')[2]));
            }
            else
            {
                list.Add(type);
            }
            return PartialView("~/Views/Shared/CalendarFree.ascx", list);
        }
        #endregion

        #region //自动完成 (线路列表,目的地列表)

        public List<Dictionary<string, object>> getTreeListById(string q, string destType, string busiType)
        {
            string selectFields = "destId,title,parentId";
            StringBuilder conditions = new StringBuilder();
            conditions.Append(" isValid = 1");
            //conditions.AppendFormat(" and destType={0} ", Utils.StrToInt(destType, 0).ToString());
            conditions.AppendFormat(" and busiType={0} ", Utils.StrToInt(busiType, 0).ToString());
            conditions.AppendFormat(" and title like '%{0}%' ", q);
            string orderFields = "orderSeq";
            return CommonBLL.GetList("Base_ProTree", selectFields, orderFields, conditions.ToString());
        }

        /// <summary>
        /// 目录树[自动完成]
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult GetTreeListBykeys(string q, string d, string b)
        {
            q = HttpUtility.UrlDecode(q);
            return Content(AutoComplete(getTreeListById(q, d, b), "title", "destId"));
        }
//
        public string AutoComplete(List<Dictionary<string, object>> l, string columnName, string idName)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("[");
            foreach (Dictionary<string, object> d in l)
            {
                sb.Append("{");
                sb.AppendFormat("\"name\":\"{0}\",", Utils.ToDBC(d[columnName].ToString().Replace("\"", "'").Trim()));
                sb.AppendFormat("\"id\":\"{0}\"", d[idName]);
                sb.Append("},");
            }
            if (l.Count > 0)
                sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }
        #endregion

        #region //[控件]根据业务类型，目的地类型 返回(后台目录树,产品所属系列)
        //返回后台目录树
        public ActionResult RetTree(
            string dest,
            string busi,
            string c,
            string n,
            string m
            )
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("d", dest);
            d.Add("b", busi);
            d.Add("c", c);
            d.Add("n", n);
            d.Add("m", m);
            return PartialView("~/Views/Shared/Sys/TreeControl.ascx", d);
        }
        //返回产品所属系列
        public ActionResult RetProBeType(
            string t,
            string d,
            string b,
            string w,
            string cName,
            string val
            )
        {
            ViewData["s"] = "";
            if (val != "")
                ViewData["selectId"] = Utils.StrToInt(val, 0);
            return PartialView("~/Views/Shared/SelectControl.ascx", selectControlBLL.getProSeries2(t,d, b,w));
        }
        //返回产品所属系列
        public ActionResult RetPlays(
            string d,
            string b,
            string w,
            string cName,
            string val,
            string pId
            )
        {
            ViewData["s"] = cName;
            if (val != "")
                ViewData["selectId"] = Utils.StrToInt(val, 0);
            return PartialView("~/Views/Shared/SelectControl.ascx", selectControlBLL.getProSeries(d, b, w, pId));
        }
        #endregion


       



    }
}
